import React, {useContext} from "react";
import {appSetStateContext} from "../AppState.tsx";
import {RobotProps} from "./Robot.tsx";

/**
 * 高阶组件使用 with 开头
 * @param ChildComponent
 */
export const withAddToCart = (ChildComponent: React.ComponentType<RobotProps>) => {
    return (props:RobotProps) => {
        const setState = useContext(appSetStateContext)
        const addToCart = (id:number,name:string)=>{
            if(setState){
                setState(state=>{
                    return{
                        ...state,
                        shoppingCart:{
                            items:[...state.shoppingCart.items,{id,name}]
                        }
                    }
                })
            }
        }
        return <ChildComponent {...props} addToCart={addToCart} />;
    }
}

export const useAddToCart = ()=>{
    const setState = useContext(appSetStateContext)
    const addToCart = (id:number,name:string)=>{
        if(setState){
            setState(state=>{
                return{
                    ...state,
                    shoppingCart:{
                        items:[...state.shoppingCart.items,{id,name}]
                    }
                }
            })
        }
    }
    return addToCart;
}